<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\JsonResponse;
use App\http\Services\Admin\MenuService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    /**
     * 列表数据
     */
    public function index(MenuService $menuService): JsonResponse
    {
        return success(data: ['tree' => $menuService->tree()]);
    }

    /**
     * 创建
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request, MenuService $menuService): JsonResponse
    {
        $params = $this->validateParams($request);
        $menuService->insertOrUpdate(0, $params);
        return success();
    }

    /**
     * 更新
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(int $id, Request $request, MenuService $menuService): JsonResponse
    {
        $params = $this->validateParams($request);
        $menuService->insertOrUpdate($id, $params);
        return success();
    }

    /**
     * 删除
     */
    public function destroy(int $id, MenuService $menuService): JsonResponse
    {
        $menuService->delete($id);
        return success();
    }

    /**
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateParams(Request $request): array
    {
        $params = $this->validate($request, [
            'pid' => 'required|integer',
            'title' => 'required|string|max:20',
            'code' => 'nullable|string|max:20',
            'component' => 'required|string|max:40',
            'type' => 'required|integer|in:1,2,3',
            'icon' => 'nullable|string|max:20',
            'path' => 'nullable|string|max:20',
            'order' => 'nullable|integer',
            'hidden' => 'required|integer|in:1,0'
        ]);
        $params['icon'] ??= '';
        $params['order'] ??= 0;
        return $params;
    }
}
